﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Accessctl.Interfaces.AccessCtl;
using PARK.Accessctl.Entitys;
using PARK.Accessctl.Entitys.Dto.AccessCtl;
using System.Text;
using System.Data;

namespace PARK.Accessctl.AccessCtl
{
    /// <summary>
    /// 时钟同步记录
    /// </summary>
    [ApiDescriptionSettings(Tag = "Equ", Name = "clocksyn", Order = 200)]
    [Route("api/Equ/[controller]")]
    public class EquclocksynService : IEquclocksynService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EquclocksynEntity> _equclocksynRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="EquclocksynService"/>类型的新实例
        /// </summary>
        public EquclocksynService(
            ISqlSugarRepository<EquclocksynEntity> equclocksynRepository,
            IUserManager userManager)
        {
            _equclocksynRepository = equclocksynRepository;
            _db = _equclocksynRepository.Context;
            _userManager = userManager;
        }
        /// <summary>
        /// 获取记录详情
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<EquclocksynEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<EquclocksynInfoOutput>();
            return output;
        }
        /// <summary>
		/// 获取时钟同步记录列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] EquclocksynQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "dbDate" : input.sidx;
                //同步时钟时间
                List<string> querySyntime = input.lastSyntime != null ? input.lastSyntime.Split(',').ToObeject<List<string>>() : null;
                DateTime? startSyntime = querySyntime != null ? Ext.GetDateTime(querySyntime.First()) : null;
                DateTime? endSyntime = querySyntime != null ? Ext.GetDateTime(querySyntime.Last()) : null;
                var data = await _db.Queryable<EquclocksynEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .WhereIF(!string.IsNullOrEmpty(input.equType), p => p.equType.Equals(input.equType))
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.equSN.Contains(input.keyword) || p.equName.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.doorAreaId), p => p.DoorAreaId.Equals(input.doorAreaId))
                    //同步时钟时间
                    .WhereIF(querySyntime != null, a => a.LastSyntime >= new DateTime(startSyntime.ToDate().Year, startSyntime.ToDate().Month, startSyntime.ToDate().Day, 0, 0, 0))
                    .WhereIF(querySyntime != null, a => a.LastSyntime <= new DateTime(endSyntime.ToDate().Year, endSyntime.ToDate().Month, endSyntime.ToDate().Day, 23, 59, 59))
                    .Select(it => new EquclocksynListOutput
                    {
                        Id = it.Id,
                        equId = it.equId,
                        equName = it.equName,
                        equSN = it.equSN,
                        dbDate = it.dbDate,
                        Description = it.Description,
                        DoorAreaId = it.DoorAreaId,
                        DoorAreaName = it.DoorAreaName,
                        Ctlposition = it.Ctlposition,
                        equType = it.equType,
                        IsSyntime = it.IsSyntime,
                        LastSyntime = it.LastSyntime
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EquclocksynListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EquclocksynEntity>().FirstAsync(p => p.Id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                try
                {
                    await _db.Deleteable<EquclocksynEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
    }
}
